package cn.itcast.springMVC.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.itcast.springMVC.domain.Category;
import cn.itcast.springMVC.domain.Post;
import cn.itcast.springMVC.service.PostService;

/**
 * 请求参数封装、请求路径映射
 * @author 16604
 *
 */
//处理请求控制器
@Controller
public class PostController {
	
	@Autowired
	PostService postService;
	
	@RequestMapping("/pages/list")		//配置请求映射
	public ModelAndView list() {
		//查询所有文章
		
		//findAll
		List<Post> posts = postService.findByAll();
		
		//跳转到文章对应的jsp页面，并把文章列表显示出来
		ModelAndView modelAndView = new ModelAndView();	//跳到哪个页面，显示具体的数据
		
		modelAndView.setViewName("posts");			//url
		
		modelAndView.addObject("posts", posts);	//data
		
		return modelAndView;
	}
	
	@RequestMapping("/pages/list_json")		//配置请求映射
	@ResponseBody		//把返回的数据json序列化
	public List<Post> listJson() {
		
		//findAll
		List<Post> posts = findAll();
		
		return posts;
	}
	
	//查询文章
	public List<Post> findAll(){
		
		List<Post> list = new ArrayList<>();
		
		Category category = new Category();
		category.setName("java");
		
		for(int i = 0;i<10;i++) {
			
			Post post = new Post();
			post.setId(i+1);
			post.setTitle("java spring mvc"+i);
			post.setCreated(new Date());
		
			list.add(post);
			
		}
		
		return list;
		
	}
	
	//访问
	@RequestMapping("/pages/edit_form")
	public String editForm(Model model) {
		model.addAttribute("id", 1);
		
		return "post_form";
	}
	
	//编辑
	@RequestMapping("/pages/edit")
	public String edit(Post post) {
		
		System.out.println("post:"+post);
		
		System.out.println(post.getCategory());
		
		return "success";
	}
}
